import { Controller, Post, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { OpenService } from './open.service';
import { v4 as uuidv4 } from 'uuid';
import { Public } from '@/common/decorators/public.decorator';

@Controller()
export class OpenController {
  constructor(private readonly openService: OpenService) { }

  @Public()
  @Post('open-api/chat/message')
  async streamChat(@Res() res: Response) {
    const taskId = uuidv4();
    const messageId = uuidv4();
    const conversationId = uuidv4();

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    const messageHandler = (message: any) => {
      res.write(`data: ${JSON.stringify(message)}\n\n`);
      if (message.event === 'message_end' || message.event === 'error') {
        this.openService.unsubscribeFromMessages(messageHandler);
        res.end();
      }
    };

    try {
      this.openService.subscribeToMessages(messageHandler);
      await this.openService.processChat(taskId, messageId, conversationId);
    } catch (error) {
      const errorEvent = {
        event: 'error',
        task_id: taskId,
        message_id: messageId,
        status: HttpStatus.INTERNAL_SERVER_ERROR,
        code: 'INTERNAL_ERROR',
        message: error.message
      };
      res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
      this.openService.unsubscribeFromMessages(messageHandler);
      res.end();
    }
  }

}
